package com.common.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author nickevin@gmail.com
 * 
 */
public class GzipFilter implements Filter {

    public GzipFilter() {}

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            String header = httpRequest.getHeader("accept-encoding");
            if (header != null && header.indexOf("gzip") != -1) {
                GzipResponseWrapper gzipResponse = new GzipResponseWrapper(
                        httpResponse);
                filterChain.doFilter(request, gzipResponse);
                gzipResponse.finishResponse();

                return;
            }

            filterChain.doFilter(request, response);
        }
    }

    public void init(FilterConfig filterconfig) {}

    public void destroy() {}
}